import { createFiber } from "./createFiber";
import { renderWithHooks } from "./hooks";
import { isArray, isStr, isStringOrNumber, Update, updateNode } from "./utils";

export function updateHostComponent(wip) {
  if (!wip.stateNode) {
    wip.stateNode = document.createElement(wip.type);
    updateNode(wip.stateNode, {}, wip.props);
  }

  reconcileChildren(wip, wip.props.children);
}
export function updateFunctionComponent(wip) {
  renderWithHooks(wip);
  const children = wip.type(wip.props);
  reconcileChildren(wip, children);
}

export function updateFragmentComponent(wip) {
  reconcileChildren(wip, wip.props.children);
}

// old 1 2 3 4
// new 2 3 4
/**
 * @param returnFiber 当前fiber 
 * @param children 当前fiber的子节点 props.children 属性
*/
function reconcileChildren(returnFiber, children) {
  if (isStringOrNumber(children)) {
    return;
  }
  const newChildren = isArray(children) ? children : [children];
  let previosNewFiber = null;
  let oldFiber = returnFiber.alternate && returnFiber.alternate.child;
  for (let i = 0; i < newChildren.length; i++) {
    const newChild = newChildren[i];
    const newFiber = createFiber(newChild, returnFiber);
    const same = sameNode(newFiber, oldFiber);
    if (same) {
      Object.assign(newFiber, {
        alternate: oldFiber,
        stateNode: oldFiber.stateNode,
        flags: Update,
      });
    }
    if (oldFiber) {
      oldFiber = oldFiber.sibling;
    }
    if (previosNewFiber === null) {
      returnFiber.child = newFiber;
    } else {
      previosNewFiber.sibling = newFiber;
    }

    previosNewFiber = newFiber;
  }
}

// 判断节点是否可以复用
function sameNode(a, b) {
  return !!(a && b && a.key === b.key && a.type === b.type);
}
